<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.push_channel_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template #pushType="{ row }">
        <el-tag size="large" style="cursor:pointer">{{ getPushTypeName(row.pushType) }}</el-tag>
      </template>
      <template #pushParam="{ row }">
        <el-text size="small" type="info">{{ row.pushParam }}</el-text>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove} from "@/api/iot/push/channel";
import {mapGetters} from "vuex";
import {validatenull} from "@/utils/validate";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      pushTypeData: [{
        label: '企业微信',
        value: 1
      }, {
        label: '钉钉',
        value: 2
      }, {
        label: '邮件',
        value: 3
      }, {
        label: '阿里云短信',
        value: 4
      }, {
        label: '腾讯云短信',
        value: 5
      }],
      option: {
        height: 'auto',
        calcHeight: 32,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        labelWidth: 150,
        dialogWidth: 650,
        column: [
          {
            label: "推送名称",
            prop: "pushName",
            search: true,
            width: 280,
            span: 24,
            rules: [{
              required: true,
              message: "请输入推送名称",
              trigger: "blur"
            }]
          },
          {
            label: "推送类型",
            prop: "pushType",
            type: "radio",
            dataType: "number",
            width: 120,
            value: 1,
            dicData: [],
            slot: true,
            search: true,
            span: 24,
            rules: [{
              required: true,
              message: "请选择推送类型",
              trigger: "blur"
            }]
          },
          {
            label: "webhook",
            prop: "webhook",
            type: "textarea",
            minRows: 3,
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "机器人签名",
            prop: "robotSign",
            type: "textarea",
            minRows: 2,
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "发件邮箱地址",
            prop: "senderEmail",
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "发件邮箱服务器",
            prop: "emailHost",
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "发件邮箱服务器端口",
            prop: "emailPort",
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "用户名",
            prop: "username",
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "邮箱密码",
            prop: "password",
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "收件邮箱地址",
            prop: "recipientEmail",
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "accessKey",
            prop: "accessKey",
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "secretKey",
            prop: "secretKey",
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "regionId",
            prop: "regionId",
            value: "cn-hangzhou",
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "appId",
            prop: "appId",
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "appKey",
            prop: "appKey",
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "短信签名",
            prop: "smsSign",
            hide: true,
            display: false,
            span: 24,
          },
          {
            label: "推送参数",
            prop: "pushParam",
            display: false,
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.push_channel_add, false),
        viewBtn: this.validData(this.permission.push_channel_view, false),
        delBtn: this.validData(this.permission.push_channel_delete, false),
        editBtn: this.validData(this.permission.push_channel_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  watch: {
    'form.pushType'() {
      const pushType = this.form.pushType;
      if (!validatenull(pushType)) {
        this.displayColumn('webhook', this.isDing() || this.isWechat());
        this.displayColumn('robotSign', this.isDing());

        this.displayColumn('senderEmail', this.isEmail());
        this.displayColumn('emailHost', this.isEmail());
        this.displayColumn('emailPort', this.isEmail());
        this.displayColumn('username', this.isEmail());
        this.displayColumn('password', this.isEmail());
        this.displayColumn('recipientEmail', this.isEmail());

        this.displayColumn('accessKey', this.isAliSms());
        this.displayColumn('secretKey', this.isAliSms());
        this.displayColumn('regionId', this.isAliSms());

        this.displayColumn('appId', this.isTencentSms());
        this.displayColumn('appKey', this.isTencentSms());

        this.displayColumn('smsSign', this.isAliSms() || this.isTencentSms());
      }
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      const column = this.findColumn("pushType");
      column.dicData = this.pushTypeData;
    },
    isWechat() {
      return this.form.pushType === 1;
    },
    isDing() {
      return this.form.pushType === 2;
    },
    isEmail() {
      return this.form.pushType === 3;
    },
    isAliSms() {
      return this.form.pushType === 4;
    },
    isTencentSms() {
      return this.form.pushType === 5;
    },
    displayColumn(prop, value) {
      const column = this.findColumn(prop)
      column.display = value;
    },
    findColumn(prop) {
      return this.$refs.crud.option.column.find(item => item.prop === prop);
    },
    getPushTypeName(value) {
      const item = this.pushTypeData.find(item => item.value === value);
      return item ? item.label : '未知类型';
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
